<?php
/**
 * Created by Zhy
 * User: Zhy
 * Date: 2018/8/2
 * Time: 10:30
 */

namespace app\home\controller;


use app\api\model\Activity as ActivityModel;//活动分类
use app\api\model\InstitutionalActivities as InstitutionalActivitiesModel;//活动
use app\api\model\Mechanism as MechanismModel;//机构
use app\api\model\MechanismMien as MechanismMienModel;//机构风采
use app\api\model\User as UserModel;
use app\api\model\Corps as CorpsModel;
use think\Db;

class Mechanism extends Common
{
    /**
     * 机构首页
     */
    public function index()
    {
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $user_id = session('u_openid');
        $params = input('param.');
//        $params['page'] = 1;
        $page = isset($params['page'])?$params['page'] : 1;
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/index?page={$page}");
        $pageNum = $page - 1;
        $userModel = new UserModel();
        $result = $userModel->joinMechanism($user_id);//所属机构ID和认证状态
        //未加入任何机构，默认为-1
//        if($result['user_to_mechanism_id'] == -1 || $result['user_attestation'] != 3) {
//            return $this->apiError(4001);
//        }
        $user_to_mechanism_id = $result['user_to_mechanism_id'];
        $user_attestation = $result['user_attestation'];
        //我的机构
        $mechModel = new MechanismModel();
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
//        if(!$result['user_to_mechanism_id']){//未登录或游客
//            return $this->apiError('w100', '暂未登录');
//        }
        $info = $mechModel->mechanismInfo($result['user_to_mechanism_id'], $field);
        //机构列表
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $list = Db::table('up_mechanism')
            ->field($field)
            ->where('mechanism_status', 2)
            ->where('mechanism_id', 'neq', 1)
            ->order('mechanism_sort desc')
            ->limit($pageNum * 10, 10)
            ->select();
        $this->assign([
            'info' => $info,
            'list' => $list,
            'user_to_mechanism_id' => $user_to_mechanism_id,
            'user_attestation' => $user_attestation
        ]);
        return $this->fetch();
    }
    
    /**
     * 获取机构详情
     * @return string|void
     * mechanism_id：机构ID
     */
    public function mechanismDetail()
    {
        $params = input('param.');
        $mechanism_id = $params['mechanism_id'];
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/mechanismDetail?mechanism_id={$mechanism_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $mechModel = new MechanismModel();
//        $this->IDIsTrue($mechanism_id, $mechModel);//判断机构ID是否存在

        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $info = $mechModel->mechanismInfo($mechanism_id, $field);//机构详情
        $activityModel = new InstitutionalActivitiesModel();
        $count = $activityModel->activityTime($mechanism_id);//总时长&总次数
        if(!$count[0]['activityTime']) {
            $info['activityTime'] = 0;
        } else {
            $info['activityTime'] = $count[0]['activityTime'];//总时长
        }
        $info['num'] = $count[0]['num'];//总次数
    
        $maxNum = $activityModel->bestActivity($mechanism_id);//最优活动
        if(empty($maxNum)) {
            $info['maxNum'] = 0;
            $info['typeName'] = '暂无活动';
        } else {
            $str = '';
            foreach($maxNum as $key=>$va){
                $str .= ltrim($va, ',');
            }
            $str = rtrim($str, ',');//所有活动类型id组合成的一个字符串
            $arr = explode(',', $str);//转换成数组
            $new_arr = array_count_values($arr);
            asort($new_arr);//将数组按升序排序
            $arr_key = array_keys($new_arr);//活动类型ID的升序数组
            $arr_value = array_values($new_arr);//活动类型次数的升序数组
            $info['maxNum'] = end($arr_value);//最优活动次数
            $activity_id = end($arr_key);//最优活动ID
            $activityTypeModel = new ActivityModel();
            $info['typeName'] = $activityTypeModel->activityTypeName($activity_id);//最优活动名称
        }
    
        //机构风采
        $list = $this->mechanismMien($params['mechanism_id']);

        //机构活动 固定显示10条
        $field = 'id, activity_name, activity_address, activity_start_time, activity_end_time,
                activity_status, activity_img, activity_id';
        $lists = Db::table('up_institutional_activities')
            ->where('activity_mechanism_id', $mechanism_id)
            ->where('activity_sh', 1)
            ->where('is_show', 1)
            ->field($field)
            ->order('create_time desc')
            ->limit(0, 10)
            ->select();
    
        $lists = $this->IDToName($lists);

        $lists = $this->getDataFormat($lists);
        $this->assign([
            'info' => $info,
            'list' => $list,
            'lists' => $lists
        ]);
        return $this->fetch();
    }
    
    /**
     * 机构风采
     * @return string|void
     * mechanism_id：机构ID
     */
    public function mechanismMien($mechanism_id){
        $params = input('param.');
        $mecModel = new MechanismModel();
        $this->IDIsTrue($mechanism_id, $mecModel);//判断机构ID是否存在
        
        $mechanismMienModel = new MechanismMienModel();
        $field = 'mien_id, mien_url, mien_description, mechanism_id';
        $list = $mechanismMienModel->mienInfo($mechanism_id, $field);//机构风采
        return $list;
    }
    
    /**
     * 获取机构的所有活动
     * @return false|\PDOStatement|string|\think\Collection|void
     * mechanism_id：机构ID
     */
    public function mechanismActivity($mechanism_id){
//        $mecModel = new MechanismModel();
//        $this->IDIsTrue($mechanism_id, $mecModel);//判断机构ID是否存在
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/mechanismActivity?mechanism_id={$mechanism_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $field = 'id, activity_name, activity_address, activity_start_time, activity_end_time, 
                activity_status, activity_img, activity_id';
        $lists = Db::table('up_institutional_activities')
            ->where('activity_mechanism_id', $mechanism_id)
            ->where('activity_sh', 1)
            ->where('is_show', 1)
            ->field($field)
            ->order('create_time desc')
            ->limit(0, 10)
            ->select();
        $lists = $this->IDToName($lists);
        $lists = $this->getDataFormat($lists);
        $this->assign([
            'lists' => $lists,
            'mechanism_id' => $mechanism_id
        ]);
        return $this->fetch();
    }
    
    /**
     * 总队
     * @return mixed
     */
    public function corps(){
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/corps");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $corpsModel = new CorpsModel();
        $info = $corpsModel->getCorpsInfo();
    
        $institutionalActivitiesModel = new InstitutionalActivitiesModel();
        $total = $institutionalActivitiesModel->totals();
    
        if(! $total[0]['totalTime']){
            $info['totalTime'] = 0;//总时长
        }else{
            $info['totalTime'] = $total[0]['totalTime'];
        }
        $info['totalNum'] = $total[0]['totalNum'];//总次数
        $this->assign('info', $info);
        return $this->fetch();
    }
    
    /**
     * 展示机构搜索页面
     * @return mixed
     */
    public function searchMec(){
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/searchMec");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        return $this->fetch();
    }
    
    /**
     * 手动输入机构名称进行查询
     * name：输入的名称
     * page：当前页码
     */
    public function searchMecList(){
        $params = input('param.');
        $key = $params['key'];
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/searchMecList?key={$key}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $list = Db::table('up_mechanism')
            ->field('mechanism_id, mechanism_name, mechanism_intro, mechanism_logo')
            ->where('mechanism_name', 'like', "%".$key."%")
            ->where('mechanism_status', 2)
            ->where('mechanism_id', 'neq', 1)
            ->order('mechanism_sort desc')
            ->limit(0, 10)
            ->select();
        $this->assign([
            'list' => $list,
            'key' => $key
        ]);
        return $this->fetch();
    }
    
    /**
     * ajax上拉/下拉刷新机构列表
     * page:当前页码
     */
    public function ajaxMechanism($page)
    {
        $mechModel = new MechanismModel();
        $field = 'mechanism_id, mechanism_name, mechanism_intro, mechanism_logo';
        $list = $mechModel->mechanismInfo('', $field, $page);//机构列表
        return json(['status'=>200, 'msg'=>$list]);
    }
    
    /**
     * ajax上拉/下拉刷新活动列表
     * @param $page
     * @return \think\response\Json
     */
    public function ajaxMechanismActivity($page, $mechanism_id){
        $field = 'id, activity_name, activity_address, activity_start_time, activity_end_time, 
                activity_status, activity_img, activity_id';
        $lists = Db::table('up_institutional_activities')
            ->where('activity_mechanism_id', $mechanism_id)
            ->where('activity_sh', 1)
            ->where('is_show', 1)
            ->field($field)
            ->order('create_time desc')
            ->limit(($page - 1) * 10, 10)
            ->select();
        $lists = $this->IDToName($lists);
        $lists = $this->getDataFormat($lists);
        return json(['status'=>200, 'msg'=>$lists]);
    }
    
    /**
     * ajax获取机构名称列表  用于搜索
     * @return string
     */
    public function ajaxMechanismList(){
        $mecModel = new MechanismModel();
        $list = $mecModel->getMechanismList();
        return json(['status'=>200, 'data'=>$list]);;
    }
    
    /**
     * 手动搜索后，ajax刷新机构列表
     * @return \think\response\Json
     */
    public function ajaxSearchMechanismList(){
        $params = input('param.');
        $key = $params['key'];
        $page = $params['page'];
        $list = Db::table('up_mechanism')
            ->field('mechanism_id, mechanism_name, mechanism_intro, mechanism_logo')
            ->where('mechanism_name', 'like', "%".$key."%")
            ->where('mechanism_status', 2)
            ->where('mechanism_id', 'neq', 1)
            ->order('mechanism_sort desc')
            ->limit(($page - 1) * 10, 10)
            ->select();
        return json(['status'=>200, 'msg'=>$list]);
    }
    
    /**
     * 判断获取的机构ID是否存在
     * @param $mechanism_id  机构ID
     * @param $model   机构模型
     */
    protected function IDIsTrue($mechanism_id, $model){
        $result = $model->mechanismInfo($mechanism_id);
        if(!$result) {
            return $this->apiError(4002);
        }
    }
    
    /**
     * 获取时期表达格式
     * @param $list
     * @return mixed
     */
    public function getDataFormat($list){
        foreach($list as $k=>&$v){
            $time_Y = date('Y');//当前的年
            $time_m = date('m');//当前的月
            $time_d = date('d');//当前的日
            $start_time = strtotime($v['activity_start_time']);
            $start_Y = date('Y', $start_time);//活动开始的年
            $start_m = date('m', $start_time);//活动开始的月
            $start_d = date('d', $start_time);//活动开始的日
            $start_Hi = date('H:i', $start_time);//活动开始的时分
            $end_time = strtotime($v['activity_end_time']);
            $end_Y = date('Y', $end_time);//活动结束的年
            $end_m = date('m', $end_time);//活动结束的月
            $end_d= date('d', $end_time);//活动结束的日
            $end_Hi = date('H:i', $end_time);//活动结束的时分
            if($time_Y == $start_Y && $time_Y == $end_Y){//今年
                if($start_m == $end_m && $start_d == $end_d){//不跨天
                    $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                    $v['activity_end_time'] = $end_Hi;
                }else{//跨天
                    $v['activity_start_time'] = $start_m . '-' . $start_d . ' ' . $start_Hi;
                    $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                }
            }else{//不同年
                if($start_m == $end_m && $start_d == $end_d){//不跨天
                    $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                    $v['activity_end_time'] = $end_m . '-' . $end_d . ' ' . $end_Hi;
                }else{//跨天
                    $v['activity_start_time'] = $start_Y . '-' . $start_m . '-' . $start_d . ' ' . $start_Hi;
                    $v['activity_end_time'] = $end_Y . '-' . $end_m . '-' . $end_d . ' ' . $end_Hi;
                }
            }
        }
        return $list;
    }
    
    /**
     * 将活动类型ID转换成活动类型名称
     * @param $lists
     * @return mixed
     */
    public function IDToName($lists){
        foreach($lists as $key=>&$list){
            $list['activity_id'] = trim($list['activity_id'], ',');
            $activity_name = Db::table('up_activity')->where('id', 'IN', $list['activity_id'])->column('activity_name');
            $list['activity_type_name'] = implode(',', $activity_name);
        }
        return $lists;
    }
    
    /**
     * 机构风采大图
     * @return mixed
     */
    public function mecMien(){
        $params = input('param.');
        $mechanism_id = $params['mechanism_id'];
        session('target_url',"http://south.xuanwumobile.com/home/Mechanism/mecMien?mechanism_id={$mechanism_id}");
        $openid = $this->getOpenid();
        $this->getUserId($openid);
        $mechanismMienModel = new MechanismMienModel();
        $field = 'mien_id, mien_url, mien_description, mechanism_id';
        $list = $mechanismMienModel->mienInfo($mechanism_id, $field);//机构风采
        $this->assign([
            'list' => $list,
            'mechanism_id' => $mechanism_id
        ]);
        return $this->fetch();
    }
}